
import '../lib/jquery.js'
import {ajax} from '../utils/ajax.js'
import { usernameTest, passwordTest, nickTest } from "./reg.js";

//表单提交时
$('form').on('submit', async e => {

    //阻止事件默认行为
    e.preventDefault();

    //获取表单 trim() 去头尾空格
    let username = $('.username').val().trim();
    let password = $('.password').val().trim();
    let rpassword = $('.rpassword').val().trim();
    let nickname = $('.nickname').val().trim();

    //验证密码格式是否正确与是否为空
    if (username == '' || password == '' || rpassword == '' || nickname == '') return alert('不能留空');
    if (!usernameTest(username)) return alert('用户名格式错误');
    if (!passwordTest(password)) return alert('密码格式错误');
    if (!nickTest(nickname)) return alert('昵称格式错误');
    if (password != rpassword) return alert('密码不一致');

    //发送的数据
    let data = {username, password, rpassword, nickname}
    let response = await ajax.post('/users/register', data);
    if (response.data.code != 1) return $('.error').css('display', 'block');

    //成功跳转到登录页面
    alert('注册成功，点击确定跳转到登录页面')
    location.href = './login.html';
})